const express = require('express');
const r = express.Router();
const pool = require('../pool.js');
// 查询商品列表接口
r.get('/list', (req, res, next) => {

  pool.query('select * from list', (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 0,
        msg: "查询失败"
      });
    } else {
      res.send({
        code: 1,
        msg: "查询成功",
        data: result
      });
    }
  });

});
// 查询地址接口
r.get('/address/:id', (req, res, next) => {
  var obj = req.params;
  pool.query('select * from uaddress where id=? ', [obj.id], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.length == 0) {
      res.send({
        code: 0,
        msg: "查询失败"
      });
    } else {
      res.send({
        code: 1,
        msg: "查询成功",
        data: result
      });
    }
  });
});
// 增加地址
r.post('/addaddress', (req, res, next) => {
  var obj = req.body;
  pool.query('insert into uaddress set ?', [obj], (err, result) => {
    if (err) { next(err); return; }
    if (result.affectedRows == 0) {
      res.send({
        code: 0,
        msg: "添加失败"
      });
    } else {
      res.send({
        code: 1,
        msg: "添加成功",
        data: result
      });
    }
  });
});
// 删除地址   http://127.0.0.1:8080/pro/del?id=6
r.delete('/del', (req, res, next) => {
  var obj = req.query;
  pool.query('delete from uaddress where id=?',[obj.id], (err, result) => {

    if (err) {
      next(err);
      return;
    }
    if (result.affectedRows == 0) {
      res.send({
        code: 0,
        msg: "删除失败"
      });
    } else {
      res.send({
        code: 1,
        msg: "删除成功"
      });
    }
  });
});

// 修改地址
r.put('/edit', (req, res, next) => {
  var obj = req.body;
  console.log(obj);
  pool.query('update uaddress set phone=? where id=? ', [obj.phone, obj.id], (err, result) => {
    if (err) {
      next(err);
      return;
    }
    if (result.affectedRows == 0) {
      res.send({
        code: 0,
        msg: "修改失败"
      });
    } else {
      res.send({
        code: 1,
        msg: "修改成功"
      });
    }

  });
});
module.exports = r;